<template>
  <el-dialog :modelValue="modelValue"
             :title="title === true ? '添加角色' : '修改角色' "
             :draggable="true"
             :destroy-on-close="true"
             @close="onClose">
    <el-form :model="form" :rules="rules" label-width="auto" style="max-width: 600px">

      <el-form-item label="角色名称" prop="roleName">
        <el-input v-model="form.roleName" placeholder="请输入角色名称" />
      </el-form-item>


      <el-form-item prop="roleKey" label="权限字段">
        <el-input v-model="form.roleKey" placeholder="请输入权限字符" />
      </el-form-item>


      <el-form-item label="角色顺序" prop="roleSort">
        <el-input-number v-model="form.roleSort" :step="1" :min="0"/>
      </el-form-item>

      <el-form-item label="状态">
        <el-radio-group v-model="form.status">
          <el-radio :key="'0'" :label="'0'">正常</el-radio>
          <el-radio :key="'1'" :label="'1'">停用</el-radio>
        </el-radio-group>
      </el-form-item>


      <el-form-item label="菜单权限">
        <el-checkbox
            v-model="menuPerm.menuExpand"
            @change="handleCheckedTreeExpand($event)"
        >展开/折叠
        </el-checkbox>
        <el-checkbox
            v-model="menuPerm.menuNodeAll"
            @change="handleCheckedTreeNodeAll($event)"
        >全选/全不选
        </el-checkbox>
        <br/>
        <el-tree
            style="max-width: 600px"
            ref=menu
            class="tree-border"
            :data="menuTreeData?.data.data"
            show-checkbox
            node-key="menuId"
            :check-strictly="false"
            empty-text="加载中，请稍候"
            :props="formParameter"
        />
      </el-form-item>


      <el-form-item label="备注">
        <el-input v-model="form.remark" type="textarea"/>
      </el-form-item>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-form>
  </el-dialog>
</template>

<script setup>
import {reactive, ref} from 'vue'
import {useRequest} from 'vue-request'
import {menuTreeselect, saveRoleMenu, updateRole} from "@/api/sys/role.js";
import {resetForm} from "@/utils/sg.js";
import {toRaw, toValue} from "@vue/reactivity";

const menu = ref();

const formParameter = {
  label: 'label',
  children: 'children',
}


const props = defineProps({
  //控制显示
  modelValue: '',
  //查询参数
  form: {},
  //菜单列表开关
  menuPerm: {},
  title: undefined
})

function echo(data) {
  data?.forEach((v) => {
    menu.value.setChecked(v, true, false)
  })
}

defineExpose({echo})


const {data: menuTreeData} = useRequest(() => menuTreeselect())

const emit = defineEmits([
  'update:modelValue',
  'update:menuPerm',
  'update:form',
  'update:formParameter',
  'search'
])

//确认
async function submitForm() {
  props.form.menuIds = []
  if (props.form.roleId !== undefined) {
    //修改
    props.form.menuIds = getMenuAllCheckedKeys()
    await updateRole(props.form).then((res) => {
    
      emit('search')
    })
  } else {
    //新增
    props.form.menuIds = getMenuAllCheckedKeys()
    await saveRoleMenu(props.form).then((res) => {
     
      emit('search')
    })
  }
  emit('update:modelValue', false)
}


//取消
function cancel() {
  reset()
  emit('update:modelValue', false)
}

function onClose() {
  reset()
  emit('update:modelValue', false)
}


// 树权限（展开/折叠）
function handleCheckedTreeExpand(value) {
  const treeList = menuTreeData?.value.data.data
  console.log("treeList",treeList);
  
  for (let i = 0; i < treeList.length; i++) {
    menu.value.store.nodesMap[treeList[i].menuId].expanded = value
  }
}

// 树权限（全选/全不选）
function handleCheckedTreeNodeAll(value) {
  menu.value.setCheckedNodes(value ? menuTreeData?.value.data.data : [])
}

// 所有菜单节点数据
function getMenuAllCheckedKeys() {
  // 目前被选中的菜单节点
  const checkedKeys = menu.value.getCheckedKeys()
  // 半选中的菜单节点
  const halfCheckedKeys = menu.value.getHalfCheckedKeys()
  checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys)
  return checkedKeys
}


// 表单重置
function reset() {
  if (menu.value !== undefined) {
    menu.value.setCheckedKeys([])
  }

  // eslint-disable-next-line no-sequences
  // (props.menuPerm.menuNodeAll = false),
  //     (props.menuPerm.menuExpand = false),
  //     (props.form = {
  //       id: undefined,
  //       roleName: undefined,
  //       roleKey: undefined,
  //       roleSort: 0,
  //       status: '0',
  //       menuIds: [],
  //       remark: undefined
  //     })
  // resetForm(props.form)
  emit('update:menuPerm', {
    menuOptions: [],
    menuExpand: false,
    menuNodeAll: false,
  })
  emit('update:form', {
    roleId: undefined,
    roleName: '',
    roleKey: '',
    roleSort: 1,
    status: '0',
    menuIds: [],
    remark: ''
  })

}


// 表单校验
const rules = {
  roleName: [
    {required: true, message: '角色名称不能为空', trigger: 'blur'}
  ],
  roleKey: [
    {required: true, message: '权限字符不能为空', trigger: 'blur'}
  ],
  roleSort: [
    {required: true, message: '角色顺序不能为空', trigger: 'blur'}
  ]
}


</script>